<template>
  <div>
    <!-- 表格部分 -->
    <el-table
      ref="singalTable"
      v-loading="listLoading"
      :data="list"
      :stripe="true"
      fit
      highlight-current-row
      :height="tableHeight"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      :summary-method="getSummaries"
      show-summary
      @selection-change="handleSelectionChange"
    >
      <template slot="empty">
        <tableEmpty />
      </template>
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        type="index"
        align="center"
        width="55"
        label="序号"
      />
      <el-table-column
        label="生成状态"
        align="center"
        width="80"
        
      >
        <template slot-scope="{row}">
          <span :style="{ color: row.contpay === 1 ? 'red' : 'black' }" >{{ row.status | statusFilter() }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="单位编码"
        align="center"
        width="110"
        
      >
        <template slot-scope="{row}">
          <span :style="{ color: row.contpay === 1 ? 'red' : 'black' }" style="float: center">{{ row.agency_code }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="单位名称"
        align="center"
         width="500"
        
      >
        <template slot-scope="{row}">
          <span :style="{ color: row.contpay === 1 ? 'red' : 'black' }" style="float: center">{{ row.agency_name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="year"
        label="年份"
        align="center"
      />
      <el-table-column
      prop="s1"
        label="实发工资"
        align="center"
      >
        <template slot-scope="{row}">
          <span style="float: right">{{ Number(row.s1).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="personCount"
        label="人数"
        align="center"
      />
    </el-table>
  
    <!-- 分页 -->
    <pagination
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <ApprovalProcess ref="app" />
    <uploadLoadSalary v-if="upload_load" ref="uploadLoadSuccess" :params="listQuery" :object="object"  :api="'getProgressSalary'" @close="uploadClose" />
  </div>
</template>

<script>
import {getSalaryList} from '@/api/thirteen/financialVerify'
import {
  revokeSalaryData,
  getBankDataStatus,
  checkSalaryData
} from '@/api/thirteen/generateSalaryData'
import { getAgencyBank } from '@/api/baseInfo'
// 分页
import uploadLoadSalary from './uploadLoadSalary'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import tableEmpty from '@/components/table/empty'
import ApprovalProcess from '@/components/ApprovalProcess/ApprovalProcessThirteen'
export default {
  name: 'Unit',
  components: { Pagination, tableEmpty, ApprovalProcess, uploadLoadSalary },
  filters: {
    statusFilter(type) {
      if (type == '0') {
        return '未生成'
      } else if (type == '1') {
        return '已生成'
      }
    }
  },
  props: ['tabPane'],
  data() {
    return {
      tableHeight: null,
      that: this,
      dialogStatus: '',
      agencyBankLists: [], // 银行
      list: [],
      total: 0,
      listLoading: true,
      object:{},
      sums:[],
      listQuery: {
        api:'getProgressSalary',
        page: 1,
        limit: 500,
        flag: '0',
        changeAgency: '',
        salaryType: '',
        agencyId: '0',
        agencySelected:'',
        bank:'',
        menuId: this.$router.currentRoute.meta.menuid,
        menuName:this.$router.currentRoute.meta.menuname
      },
      ifShowMessage: false,
      upload_load: false,
      selected_list: [] // 表格数据源
    }
  },
  watch: {
    list(val) {
      this.doLayout()
    }
  },
  mounted() {
    this.getTbHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
  },
  // 加载后运行
  created() {
    // 获取参数
    this.listQuery.flag = this.tabPane
    // 加载获取全部数据
    this.getList()
    this.initBaseInfo()
  },
  methods: {
    show() {
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择要生成工资数据的单位',
          type: 'warning',
          duration: 4000
        })
      this.$emit('makeSalaryDataCallback')
        return
      }
      let sumAgency=0
      let sumRealSalary=0
      let personCount=0
      const _that=this
       _that.listQuery.agencySelected = ''
      sumAgency=selection.length
      selection.forEach(function(item, index){
        
        if(item.no==='合计'){
          sumAgency-=1
        }else{
        if(index===0){
          _that.listQuery.agencySelected+=item.agency_id
        }else{
          _that.listQuery.agencySelected+=','+item.agency_id
        }  
         
        sumRealSalary+=Number(item.s1)
        personCount+=Number(item.personCount)
        }
      })
     this.object.agencyCount=sumAgency
     this.object.sumRealSalary=Number(sumRealSalary).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") 
     this.object.personCount=personCount
      const h = this.$createElement;
      this.$msgbox({
          title: '是否确认生成',
          message: h('span', null,[
            h('span', {class:'messagestyle'}, '当前生成单位数'),
            h('span', null, '\u3000:\u3000'+sumAgency),
            h('br', null,),
            h('span', {class:'messagestyle'}, '当前生成金额'),
            h('span', null, '\u3000:\u3000'+Number(sumRealSalary).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")),
            h('br', null,),
            h('span', {class:'messagestyle'}, '当前生成人数'),
            h('span', null, '\u3000:\u3000'+Number(personCount) ),
          ]),
          dangerouslyUseHTMLString: true,
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              done();
              this.ifShowMessage = false
              this.upload_load = true
            } else {
              this. uploadClose()
              done();
            }
          }
        }).then(action => {
          done();
          this.$message({
            type: 'info',
            message: 'error: ' + action
          });
        });
      
    },

    // 进度条走完，关闭弹窗，调用展示提示信息的方法
    uploadClose() {
      this.upload_load = false
      this.listQuery.agencySelected=''//批量生成完后清空选择值，再调查询方法，否则会报414
      this.getMessage()
      this.getList()
      this.$emit('makeSalaryDataCallback')
    },
    // 展示附件返回信息
    getMessage() {
      if (this.ifShowMessage) { // 成功
        this.$message({
          message: '生成成功',
          type: 'success',
          showClose: true,
          duration: 4000
        })
        this.handleQuery()
      }
    },
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    doPayLayout() {
      this.$nextTick(() => {
        this.$refs.payTable.doLayout()
      })
    },
    getTbHeight() {
      // if (this.tabPane === '1') {
      //   this.tableHeight = window.innerHeight / 2 - 135
      // } else {
        this.tableHeight = window.innerHeight - 230
      // }
    },
    getList() {
      this.listLoading = true;
      getSalaryList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
        this.setInitRow()
        this.$emit('checkloadCallback')
      })
    },
    checkSalaryData(){
      let that=this
       const selection = this.$refs.singalTable.selection
       if (selection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择要校验工资数据的单位',
          type: 'warning',
          duration: 4000
        })
      this.$emit('checksalaryloadCallback')
        return
      }
      const operateAgency = []
      selection.forEach(item => {
        operateAgency.push(item.agency_id)
      })
      const operateAgencys = {}
      operateAgencys['agencyIds'] = operateAgency
      operateAgencys['menuid'] = this.$router.currentRoute.meta.menuid
      operateAgencys['menuname'] = this.$router.currentRoute.meta.menuname
      checkSalaryData(operateAgencys).then(response => {
        if (response && response.rscode === '100000') {
          if(response.data.request){
            this.$message({
            showClose: true,
            dangerouslyUseHTMLString: true,
            message: response.data.request,
            type: 'warning',
            duration: 0
            })
          }else{
             this.$message({
            showClose: true,
            dangerouslyUseHTMLString: true,
            message: '检验完成！无失败单位',
            type: 'success',
            duration: 2000
            })
          }
          this.list.forEach(function(item, index){
            if(that.isInArray(response.data.data,item.agency_id)){
              item["contpay"]=1
              that.$set(that.list,index,item)
             
            }
            
          })
           this.$emit('checksalaryloadCallback') 
        } else {
           this.$emit('checksalaryloadCallback') 
        }
      })
        .catch(() => {
           this.upload_load = false;
           this.ifShowMessage = false;
           this.$emit('checksalaryloadCallback') 
        })
    },
    //判断集合中是否存在某值的方法
   isInArray(arr,value){
      for(var i = 0; i < arr.length; i++){
          if(value === arr[i]){
              return true;
          }
      }
      return false;
    },
     // 获取银行基础数据
    initBaseInfo() {
      getAgencyBank().then(response => {
        this.agencyBankLists = Object.assign({}, response.data)
      })
    },
    // 审核说明
    processnode() {
      const selection = this.$refs.singalTable.selection
      if (selection.length !== 1) {
        this.$message({
          showClose: true,
          message: '请选择一条数据',
          type: 'warning',
          duration: 4000
        })
        return
      }
      if (!selection[0].agency_id) {
        selection.splice(0, 1)
      }
      this.$refs.app.getList(selection[0].agency_id)
    },
    
    // 查询
    handleQuery() {
      this.listQuery.page = 1
      // this.listQuery.limit = 10
      this.getList()
    },
    // 查询
    handleQueryBank(val) {
      this.listQuery.bank=val
      this.listQuery.page = 1
      // this.listQuery.limit = 10
      this.getList()
    },
    // 树查询
    handleTree(data) {
      this.listQuery.page = 1
      // this.listQuery.limit = 10
      this.listQuery.agencyId = data.id
      this.getList()
    },
    // 撤销生成
    revokeSalaryData() {
      const selection = this.$refs.singalTable.selection
      if (selection.length === 0) {
        this.$message({
          showClose: true,
          message: '请选择要撤销生成的单位',
          type: 'warning',
          duration: 4000
        })
        this.$emit('revokeSalaryDataCallback')
        return
      }
      const operateAgency = []
      const agencyIds = []
      selection.forEach(item => {
        operateAgency.push(item.agency_id)
        agencyIds.push(item.agency_id)
      })
      const parms = { 'agencyIds': operateAgency.join(',') }
      // 判断是否生成银行数据，如果生成则不允许撤销
      getBankDataStatus(parms).then((response) => {
        if (response.data === true) {
          this.$message({
            showClose: true,
            message: '已上传银行数据，不允许撤销',
            type: 'warning',
            duration: 4000
          })
          this.$emit('revokeSalaryDataCallback')
          return
        } else {
          const data = {}
          data['agencyIds'] = agencyIds
          data['menuid'] = this.$router.currentRoute.meta.menuid
          data['menuname'] = this.$router.currentRoute.meta.menuname
          revokeSalaryData(data)
            .then(response => {
              this.$message({
                showClose: true,
                message: '撤销生成成功',
                type: 'success',
                duration: 4000
              })
              this.handleQuery()
              this.$emit('revokeSalaryDataCallback')
            })
            .catch(e => {
              console.error(e)
              this.$emit('revokeSalaryDataCallback')
            })
        }
      })
    },
    // 设置工资列表初始选择
    setInitRow() {
      if (this.tabPane === '1') {
        this.$refs.singalTable.setCurrentRow(this.list[1])
      }
    },
  
    // 获取勾选的数据data
    handleSelectionChange(val) {
        this.selected_list = val;
      
      },
    //自定义合计
    getSummaries(param) {    
        const { columns, data } = param;      
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 1) {
            sums[index] = '合计';
            return;
          }
          if (index <6) {
            return;
          }
          let values;
          values = data.map(item => Number(item[column.property])); // 无勾选
          if (this.selected_list && this.selected_list.length > 0) { // 有勾选
          values = this.selected_list.map(item => Number(item[column.property]));
            }
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            if(index!=7){
              sums[index]= Number(sums[index]).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,")
              sums[index] += ' 元';
            }else{
              sums[index] += ' 人';
            }
           
          } else {
            sums[index] = 'N/A';
          }
        });
    
        return sums;
      }
  }
}
</script>

<style scoped>
.messagestyle {
  width: 110px;
  text-align: justify;
  display: inline-block;
  overflow: hidden;
  vertical-align: top;
}
.messagestyle:after {
  display: inline-block;
  width: 100%;
  content: " ";
  height: 0px;
}
</style>

